<template>
  <div>
    <!-- 搜索区域: 员工信息查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="">
        <el-input v-model="searchForm.empName" placeholder="员工姓名" clearable />
      </el-form-item>
      <el-form-item label="">
        <el-select v-model="searchForm.gender" placeholder="员工性别" clearable>
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input v-model="searchForm.position" placeholder="员工岗位" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作区域: 新增员工和数据导出按钮 -->
    <div style="display: inline;">
      <el-button type="primary" round @click="handleAdd">新增员工</el-button>
      <el-dialog v-model="addDialogVisible" title="新增员工信息" width="500">
        <el-form :model="newEmployee">
          <el-form-item label="员工姓名" :label-width="formLabelWidth">
            <el-input v-model="newEmployee.employeeName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="员工性别" :label-width="formLabelWidth">
            <el-select v-model="newEmployee.employeeSex"  clearable>
                  <el-option label="男" value="m"></el-option>
                  <el-option label="女" value="f"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工年龄" :label-width="formLabelWidth">
            <el-input v-model="newEmployee.employeeAge" autocomplete="off" />
          </el-form-item>
          <el-form-item label="员工岗位" :label-width="formLabelWidth">
            <el-select v-model="newEmployee.employeeDuty"  clearable>
                  <el-option label="经理" value="001"></el-option>
                  <el-option label="普通员工" value="002"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddConfirm">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <el-button type="warning" round @click="handleExport">导出数据</el-button>
    <div style="height: 20px;"></div>

    <!-- 数据展示区域: 员工信息表格 -->
    <el-table :data="tableData.resultList" border style="width: 100%" max-height="500">
      <el-table-column prop="id" sortable label="序号"  />
      <el-table-column prop="employeeName" sortable label="员工姓名"  />
      <el-table-column prop="employeeAge" sortable label="员工年龄" />
      <el-table-column prop="employeeSex" sortable label="员工性别" >
        <template #default="scope">
          {{ scope.row.employeeSex === 'm' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="employeeDuty" sortable label="员工岗位"  >
        <template #default="scope">
          {{ scope.row.employeeDuty === '1' ? '组长' : '普通员工' }}
        </template>
      </el-table-column>

      <!-- <el-table-column prop="department" sortable label="所属部门" /> -->
  
      <el-table-column prop="createTime" sortable label="创建时间" />
      <el-table-column prop="createName" sortable label="创建人" />
      <el-table-column prop="updateTime" sortable label="修改时间" />
      <el-table-column prop="updateName" sortable label="修改人" />
      
      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗: 员工信息修改 -->
    <el-dialog v-model="editDialogVisible" title="编辑员工信息" width="500">
      <el-form :model="editForm">
        <el-form-item label="员工姓名" :label-width="formLabelWidth">
          <el-input v-model="editForm.employeeName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="员工性别" :label-width="formLabelWidth">
          <el-select v-model="editForm.employeeSex" >
            <el-option label="男" value="m"></el-option>
            <el-option label="女" value="f"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工年龄" :label-width="formLabelWidth">
          <el-input v-model="editForm.employeeAge" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="员工岗位" :label-width="formLabelWidth">
          <el-input v-model="editForm.employeeDuty" autocomplete="off" >
            {{ editForm.employeeDuty === '001' ? '经理' : '普通员工' }}
          </el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页区域 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="searchCondition.pageNum"
        v-model:page-size="searchCondition.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.totalNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"                              
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'  // 添加 onMounted 引入
import { searchEmployee, addEmployee,changeEmployee,deleteEmployee} from '../api/api.js'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// ==============================

// 表格数据对象
const tableData = ref(
 [], // 当前页数据列表
)

// 对话框显示状态
const addDialogVisible = ref(false)    // 新增对话框
const editDialogVisible = ref(false)   // 编辑对话框
const formLabelWidth = '120px'         // 表单标签宽度

// 搜索表单数据
const searchForm = reactive({
  empName: '',   // 员工姓名
  gender: '',    // 性别
  position: ''   // 岗位
})

// 新增员工表单数据
const newEmployee = reactive({
  employeeName: '',     // 员工姓名
  employeeSex: '',      
  employeeAge: '',         // 年龄
  employeeDuty: '',    // 岗位
  department: '',  // 部门
  phone: '',       // 联系电话
  state: '1'       // 在职状态（1-在职，0-离职）
})

// 编辑表单数据
const editForm = reactive({

  employeeName: '',     // 员工姓名
  employeeAge: '',         // 年龄
  employeeDuty: '',    // 岗位

})

// 分页信息
// const pageInfo = reactive({
//   pageNum: 1,      // 当前页码
//   pageSize: 10     // 每页显示条数
// })


const searchCondition = {
  empName: '',   // 员工姓名
  gender: '',    // 性别
  position: '',   // 岗位
  pageNum: 1,      // 当前页码
  pageSize: 10     // 每页显示条数
}

// ==============================

/**
 * 查询员工列表
 * 根据搜索条件和分页信息获取员工数据
 */
const search = async () => {
  searchCondition.empName = searchForm.empName
  searchCondition.gender = searchForm.gender
  searchCondition.position = searchForm.position


    const res = await searchEmployee(searchCondition)
    if(res.data.code === 200) {
    ElMessage.success('查询成功')
  } else {
    ElMessage.error('查询失败：' + res.data.message)
  }
    
    tableData.value = res.data.data
    console.log(tableData.value)

}

/**
 * 新增员工-打开对话框
 * 重置表单数据并显示新增对话框
 */
const handleAdd = () => {
  Object.keys(newEmployee).forEach(key => {
    newEmployee[key] = ''
  })
  newEmployee.state = '1'
  addDialogVisible.value = true
}



/**
 * 新增员工-确认提交
 * 提交新增员工表单数据到后端
 */
const handleAddConfirm = async () => {

    addEmployee(newEmployee)
    search()
    addDialogVisible.value = false

}

/**
 * 编辑员工-打开对话框
 * @param {Object} row 当前行员工数据
 */
const handleEdit = (row) => {
  Object.assign(editForm, row)
  editDialogVisible.value = true
}

/**
 * 编辑员工-确认提交
 * 提交编辑后的员工信息到后端
 */
const handleEditConfirm = async () => {
 
    await changeEmployee(editForm)
    search()
    editDialogVisible.value = false

}

/**
 * 删除员工
 * @param {Object} row 要删除的员工数据
 */
const handleDelete = async (row) => {
  console.log(row)

    await deleteEmployee(row.employeeCode)
    search()

}


/**
 * 改变每页显示数量
 * @param {number} val 新的每页条数
 */
const handleSizeChange = (val) => {
  
  search()
}

/**
 * 改变当前页码
 * @param {number} val 新的页码
 */
const handleCurrentChange = (val) => {

  search()
}

/**
 * 导出员工数据
 * 导出当前筛选条件下的所有员工数据
 */
const handleExport = () => {
  try {
    // 获取要导出的数据
    const exportData = tableData.value.resultList.map(item => {
      return {
        '序号': item.id,
        '员工姓名': item.employeeName,
        '员工年龄': item.employeeAge,
        '员工性别': item.employeeSex === 'm' ? '男' : '女',
        '员工岗位': item.employeeDuty === '1' ? '组长' : '普通员工',
        '创建时间': item.createTime,
        '创建人': item.createName,
        '修改时间': item.updateTime,
        '修改人': item.updateName
      }
    })

    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    // 设置列宽
    const colWidth = [
      { wch: 8 },  // 序号
      { wch: 12 }, // 员工姓名
      { wch: 10 }, // 员工年龄
      { wch: 10 }, // 员工性别
      { wch: 12 }, // 员工岗位
      { wch: 20 }, // 创建时间
      { wch: 12 }, // 创建人
      { wch: 20 }, // 修改时间
      { wch: 12 }  // 修改人
    ]
    worksheet['!cols'] = colWidth

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '员工信息表')

    // 生成excel文件
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' })
    
    // 下载文件
    saveAs(blob, `员工信息表_${new Date().getTime()}.xlsx`)

    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

onMounted(() => {
  search()
})
</script>

<style scoped>
 .demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.operation-area {
  margin: 15px 0;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}
</style>
